package com.github.aloxc.plugin.restplus.action;

import com.github.aloxc.plugin.DonotGuard;
import com.github.aloxc.plugin.restplus.action.AbstractBaseAction;
import com.github.aloxc.plugin.restplus.common.Consts;
import com.github.aloxc.plugin.restplus.common.PsiClassHelper;
import com.github.aloxc.plugin.restplus.common.PsiMethodHelper;
import com.github.aloxc.plugin.restplus.entity.EnvironmentConfig;
import com.github.aloxc.plugin.restplus.entity.RestConfig;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.github.aloxc.plugin.restplus.popup.PopupBalloon;
import com.github.aloxc.plugin.restplus.utils.JsonUtils;
import com.github.aloxc.plugin.restplus.utils.StringUtils;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.impl.ActionManagerImpl;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import org.jetbrains.kotlin.asJava.LightClassUtilsKt;
import org.jetbrains.kotlin.psi.KtNamedFunction;

import java.awt.datatransfer.StringSelection;
import java.util.List;
import java.util.Map;

import static com.intellij.openapi.actionSystem.CommonDataKeys.PSI_ELEMENT;

/**
 * 右键菜单生成并复制restful url
 * todo: 没考虑RequestMapping 多个值的情况
 * @author leero 
 */
@DonotGuard
public class CopyUrlAction extends AbstractBaseAction {
    Editor myEditor ;

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();
        myEditor = e.getData(CommonDataKeys.EDITOR);
        PsiElement psiElement = e.getData(PSI_ELEMENT);
        PsiMethod psiMethod = null;
        if(psiElement instanceof PsiMethod){
            psiMethod = (PsiMethod) psiElement;
        }else if(psiElement instanceof KtNamedFunction){
            KtNamedFunction fun = (KtNamedFunction)psiElement;
            psiMethod = LightClassUtilsKt.toLightMethods(psiElement).get(0);
        }

        //TODO: 需完善 jaxrs 支持
        String servicePath;
        Consts.ServiceType serviceType = Consts.ServiceType.getServiceType(psiMethod);
        if (serviceType == Consts.ServiceType.JAXRS) {
            servicePath = PsiMethodHelper.create(psiMethod).buildServiceUriPath();
        } else if(serviceType == Consts.ServiceType.MICRONAUT) {
            servicePath = PsiMethodHelper.create(psiMethod).buildServiceUriPathWithParams();
        }else{
            servicePath = PsiMethodHelper.create(psiMethod).buildServiceUriPathWithParams();
        }

        String tempUrl = servicePath;
        RestConfig config = RestConfig.loadConfig(project);
        EnvironmentConfig environmentConfig = null;
        if (config != null && config.getEnv() != null && config.getEnv().size() > 0) {
            Map<String, EnvironmentConfig> envMap = config.getEnv();
            for (String envName : envMap.keySet()) {
                if (envMap.get(envName).isSelected()) {
                    environmentConfig = envMap.get(envName);
                    break;
                }
            }
        }

        // 完整url
        boolean https = environmentConfig.isHttps();
        String context = environmentConfig.getContext();
        String tContext = context;
        if (!StringUtils.isNullOrEmpty(tContext)) {
            if (!tContext.startsWith("/")) {
                tContext = "/" + tContext;
            }
            if (context.endsWith("/")) {
                tContext = context.substring(0, context.length() - 1);
            }
        } else {
            tContext = "";
        }
        tempUrl = (https ? "https://" : "http://") + environmentConfig.getHost() + ":" + environmentConfig.getPort() + tContext + tempUrl;
        CopyPasteManager.getInstance().setContents(new StringSelection(servicePath));
        if(e.getPresentation().getIcon() == Consts.Icons.FULL_URL){
            CopyPasteManager.getInstance().setContents(new StringSelection(tempUrl));
            PopupBalloon.showPopupBalloon(myEditor,
                    String.format(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.copy.servicefullurl.text"),tempUrl,tempUrl),false);
        }else{
            CopyPasteManager.getInstance().setContents(new StringSelection(servicePath));
            PopupBalloon.showPopupBalloon(myEditor,
                    String.format(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.copy.servicefullurl.text"),tempUrl,servicePath),false);
        }
    }


    /**
     * spring rest 方法被选中才触发
     * @param e
     */
    @Override
    public void update(AnActionEvent e) {
        PsiElement psiElement = e.getData(CommonDataKeys.PSI_ELEMENT);

        boolean visible = false;

        if(psiElement instanceof PsiMethod){
            PsiMethod psiMethod = (PsiMethod) psiElement;
            // rest method 或标注了RestController 注解
            visible =  (PsiClassHelper.isRestController(psiMethod.getContainingClass()) && PsiMethodHelper.isRestfulMethod(psiMethod) );
        }
        if(!visible){//判断是否是kotlin方法
            if(psiElement instanceof KtNamedFunction){
                KtNamedFunction fun = (KtNamedFunction)psiElement;
                List<PsiMethod> psiMethods = LightClassUtilsKt.toLightMethods(psiElement);
                for (PsiMethod psiMethod: psiMethods) {
                    visible = (PsiClassHelper.isRestController(psiMethod.getContainingClass()) && PsiMethodHelper.isRestfulMethod(psiMethod));
                }
            }
        }
        if(visible){
            if(e.getPresentation().getText().equals("Copy Full URL") ||
                    e.getPresentation().getText().equals("拷贝请求全路径URL") ||
                    e.getPresentation().getText().equals("コピーは全パスURLを要求する")){
                e.getPresentation().setText(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.request.copyfullurl.text"));
                e.getPresentation().setDescription(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.request.copyfullurl.text"));
                e.getPresentation().setIcon(Consts.Icons.FULL_URL);
            }else{
                e.getPresentation().setText(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.request.copyurl.text"));
                e.getPresentation().setDescription(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.request.copyurl.text"));
                e.getPresentation().setIcon(Consts.Icons.URL);
            }

        }
        setActionPresentationVisible(e, visible);
    }

}
